"""
轻量级 ProgressTracker，用于为 CLI 提供学生进度/成绩汇总接口。
注：实现为最小兼容层，使用 LMSSystem 中的 user_manager 和 course_manager 提供的数据。
"""
from typing import Optional, Dict, Any


class ProgressTracker:
    def __init__(self, system):
        self.system = system

    def get_student_progress(self, student_id: str) -> Optional[Dict[str, Any]]:
        """返回学生的进度摘要，字段包括:
        - total_credits: 学生已修/已选课程的学分总和（尝试从 course.credit 获取）
        - average_grade: 学生平均成绩（取自 Student.grades）
        - completed_courses: 已完成课程数（根据成绩或其它策略估算）
        """
        if not self.system or not getattr(self.system, 'user_manager', None):
            return None

        user_mgr = self.system.user_manager
        student = user_mgr.get_user(student_id)
        if not student:
            return None

        # 平均成绩与完成课程数从 student.grades 中提取
        grades = {}
        try:
            grades = student.get_grades()
        except Exception:
            grades = getattr(student, 'grades', {}) or {}

        avg = 0.0
        completed = 0
        if grades:
            vals = [v for v in grades.values() if isinstance(v, (int, float))]
            if vals:
                avg = sum(vals) / len(vals)
                # 将有成绩的课程视为"已完成"
                completed = len(vals)

        # 计算学分总和（尝试从 course_manager 中获取credits）
        total_credits = 0
        if getattr(self.system, 'course_manager', None):
            cm = self.system.course_manager
            for cid in (list(grades.keys()) + getattr(student, 'enrolled_courses', [])):
                try:
                    course = cm.get_course(cid)
                    if course and hasattr(course, 'credits') and isinstance(course.credits, (int, float)):
                        total_credits += int(course.credits)
                except Exception:
                    continue

        return {
            'total_credits': total_credits,
            'average_grade': float(avg),
            'completed_courses': int(completed)
        }
